<?php

class Client
{
    public function call($class, $method, ...$params)
    {
        $clientSocket = @stream_socket_client('tcp://127.0.0.1:1234', $errno, $errstr);

        if (!$clientSocket) {
            exit('客户端连接创建失败:' . $errno);
        }
        stream_set_timeout($clientSocket, 2);
        // 数据包封装
        $packet = array(
            'data' => json_encode(
                array(
                    'class' => $class,
                    'method' => $method,
                    'params' => $params,
                )
            ),
        );

        $buffer = sprintf("%s", json_encode($packet));
        // 发送数据包
        $len = fwrite($clientSocket, $buffer);
        if ($len != strlen($buffer)) {
            exit("write fail");
        }

        echo "send...wait" . PHP_EOL;

        // 接收数据
        $buf = '';
        while (!feof($clientSocket)) {
            $buf .= fread($clientSocket, 1024);
            $status = stream_get_meta_data($clientSocket);
            print_r($status);
        }

        fclose($clientSocket);

        echo "close" . PHP_EOL;

        return $buf;
    }
}

$client = new Client();
try {
    $response = $client->call('RpcTest', 'test', array('name' => '张三'));
    print_r(json_decode($response, true));
} catch (\Exception $e) {
    print_r($e->getTraceAsString());
}
